<template>
  <div>
    <el-dialog
      class="add-pop add-MaterialMangePop"
      title='编辑'
      width="50%"
      @close="closeMPEPop"
      :visible.sync="dialogVisibleEdit"
      :close-on-click-modal="false">
        <el-form
          label-width="110px"
          :model="dataFormAdd"
          :rules="buryingConfigRule"
          ref="dataFormAdd"
        >
          <el-form-item label="文件名称">
              <el-input
              :disabled="true"
              v-model="dataFormAdd.name"
              auto-complete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="文件大小">
              <el-input
              :disabled="true"
              v-model="dataFormAdd.mediaSizeStr"
              auto-complete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="文件格式">
              <el-input
              :disabled="true"
              v-model="dataFormAdd.style"
              auto-complete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="文件类型">
            <el-select clearable @change="mediaTypeChange" filterable v-model="dataFormAdd.bcMediaType" filterable>
                <el-option
                  v-for="item in bcMediaTypeOption"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key"
                ></el-option>
              </el-select>
          </el-form-item>
          <!-- 当文件类型为宣传物料 -->
          <div v-if='dataFormAdd.bcMediaType==1'>
            <el-form-item label="颜色模式">
              <el-select clearable @change="mediaTypeChange" filterable v-model="dataFormAdd.mediaColourMode" filterable>
                  <el-option
                    v-for="item in mediaColourModeOption"
                    :key="item.key"
                    :label="item.value"
                    :value="item.key"
                  ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="分辨率">
              <el-select clearable @change="mediaTypeChange" filterable v-model="dataFormAdd.mediaResolution" filterable>
                  <el-option
                    v-for="item in mediaResolutionOption"
                    :key="item.key"
                    :label="item.value"
                    :value="item.key"
                  ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="文件尺寸">
              <el-select clearable @change="mediaTypeChange" filterable v-model="dataFormAdd.mediaMeasure" filterable>
                  <el-option
                    v-for="item in mediaMeasureOption"
                    :key="item.key"
                    :label="item.value"
                    :value="item.key"
                  ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="使用说明">
              <el-input
                type="textarea"
                style="heigth:39px;"
                v-model="dataFormAdd.contents"
                placeholder="请输入内容"
              ></el-input>
            </el-form-item>
            <el-form-item label="预览图">
              <WebUploadIMG
                    :fileNumLimit="fileNumLimit"
                    :fileSize="fileSize"
                    :chunkSize="chunkSize"
                    :uploadSuffixUrl="uploadSuffixUrl"
                    :options="options2"
                    :fileListData="fileList"
                    :materielId='materielId'
                    :imgUploadUrl='imgUploadUrl'
                    @uploadSuccess='uploadSuccess'
                    ref='anyName'
              ></WebUploadIMG>
            </el-form-item>
            <el-form-item label="裁剪图">
              <el-row>
                <el-col :span="16">
                  <!-- 裁剪 -->
                            <vue-cropper ref="cropper" :img="option.img" :output-size="option.size" :output-type="option.outputType" :info="true" :full="option.full"
        :can-move="option.canMove" :can-move-box="option.canMoveBox" :fixed-box="option.fixedBox" :original="option.original"
        :auto-crop="option.autoCrop" :auto-crop-width="option.autoCropWidth" :auto-crop-height="option.autoCropHeight" :center-box="option.centerBox"
				@real-time="realTime" :high="option.high" ></vue-cropper>
                </el-col>
                <el-col :span="8">
                        <h2 align="center">头像预览</h2>
                            <div class="show-preview">
                                <div  class="preview">
                                    <img :src="previews.url" >
                                </div>
                            </div>
                    </el-col>
              </el-row>
            </el-form-item>
          </div>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button :size="size" @click.native="closeMPEPop">{{$t('action.cancel')}}</el-button>
          <el-button
            :size="size"
            type="primary"
            @click.native="submitAdd('dataFormAdd')"
            :loading="editLoading"
          >提交</el-button>
        </div>
      </el-dialog>
  </div>
</template>
<script>
import CrmTable from "@/views/Core/CrmTable";
import KtButton from "@/views/Core/KtButton";
import WebUploadIMG from "@/components/common/upload/WebUploadIMG";
import { VueCropper } from "vue-cropper";
import { baseUrl } from "@/utils/global";
export default {
  name: "MaterialPackageEidtPop",
  props: {
    dataFormAdd:Object,
    dialogVisibleEdit: Boolean, //弹窗显示
    trackingNum: Number, //跟进次数
    contractDate: String, //跟进时间
    contactPeople: String, //联系人
    contractType: String, //沟通形式
    student_communication_type: Array, //沟通形式选项
    customerType:String,//客户类型
    student_type_options:Array,//客户类型选项
    customerProgress:String,//客户进展
    student_progress_options:Array,//客户进展选项
    contractContent:String,//沟通内容
    nextContractDate:String,
    trackingPeople:String,
    baseUrl:String,
  },
  components: {
    CrmTable,
    KtButton,
    VueCropper,
    WebUploadIMG
  },
  data() {
    return {
      // showTrackingPop: false, //显示跟进窗口
      date: new Date(),
      contractDate: "",
      mediaColourModeOption:[],
      bcMediaTypeOption:[],
      dialogImageUrl: '',
      dialogVisible: false,
      imageUrl: "",
      showImgVisible: false,
      uploader: {},
      uploadBtnDisabled: false,
      uploadStaus: "el-icon-upload",
      fileList: [], //显示集合
      chunked: true, //是否开启分片上传
      fileNumLimit: 3, //文件总数
      fileSize: 100 * 1024 * 1024 * 1024, //默认上传文件大小
      chunkSize: 30 * 1024 * 1024, //默认文件片段
      uploadSuffixUrl: baseUrl,
      options2: {
        compress:null,
        //允许上传的文件
        fileType:
          "",
        fileUploadUrl: "/mediaInfo/chunkUpload", //上传地址
        fileCheckUrl: "/mediaInfo/checkFile", //检测文件是否存在url
        checkChunkUrl: "/mediaInfo/checkFile", //检测分片url
        // mergeChunksUrl: "/upload/fileRecord/zone/upload/merge/", //合并文件请求地址
        headers: {}
      },
      previews:{
      
      }, //实时预览图数据
      option: {
          img: 'https://avatars3.githubusercontent.com/u/15681693',
          size: 1,
          full: false,
          outputType: 'png',
          canMove: true,
          fixedBox: false,
          original: false,
          canMoveBox: true,
          autoCrop: true,
          // 只有自动截图开启 宽度高度才生效
          autoCropWidth: 200,
          autoCropHeight: 150,
          centerBox: false,
          high: true
        },
      imgUploadUrl:'',
      fileName:'',//本机文件地址
      uploadImgRelaPath:'',//上传后图片地址
      imgbacse64:''
    };
  },
  methods: {
    handShowTracking: function() {
      this.$emit("handShowTracking", { index: index, row: row });
    },
    colseTrackingPop: function() {
      this.$emit("colseTrackingPop");
    },
    submitAdd(){
      this.$emit('submitAdd',this.dataFormAdd)
    },
    closeMPEPop(){
      this.$emit('closeMPEPop',this.dialogVisibleEdit)
    },
    mediaTypeChange(){
      
    },

    getDownList(){
      // 文件类型
      this.$api.user.optionsList({ codeType: "bc_media_type" }).then(res => {
        this.bcMediaTypeOption=res.keyValueList
      });
      // 颜色模式
      this.$api.user.optionsList({ codeType: "media_colour_mode" }).then(res => {
        this.mediaColourModeOption=res.keyValueList
      });
      // 分辨率
      this.$api.user.optionsList({ codeType: "media_resolution" }).then(res => {
        this.mediaResolutionOption=res.keyValueList
      });
      // 文件尺寸
      this.$api.user.optionsList({ codeType: "media_measure" }).then(res => {
        this.mediaMeasureOption=res.keyValueList
      });
    },
    uploadSuccess(val){
      
    
      // this.attach.customaryUrl=val
     this.preView(val)
    
     
    },
    getImageBlob(url, cb) {
        var xhr = new XMLHttpRequest();
        xhr.open("get", url, true);
        xhr.responseType = "blob";
        xhr.onload       = function() {
            if (this.status == 200) {
                if(cb) cb(this.response);
            }
        };
        xhr.send();
    },
    preView(url){
        let reader    = new FileReader(); 
        this.getImageBlob( url , function(blob){
          reader.readAsDataURL(blob)
        });
      
        reader.onload = function(e) {
            var img = document.createElement("img");
            img.src = e.target.result;
            reader.readAsArrayBuffer(url)
        }
        console.log(reader.readAsArrayBuffer(url[0].blocks[0]))
    },
   //控制弹出层关闭
        handleClose(){
            this.dialogVisible3=false
        },
        //实时预览
        realTime(data){
            this.previews=data
        },
        //加载头像信息
        find(){
            this.userId = sessionStorage.getItem('userId');
            this.$axios.post('/api/attach/find',this.attach).then(res=>{
                console.log(res);
            });
        },
        //选择本地图片
        uploadImg(e,num){
            //上传图片
          // this.option.img
          var file = e.target.files[0]
          
          if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
            alert('图片类型必须是.gif,jpeg,jpg,png,bmp中的一种')
            return false
          }
          var reader = new FileReader()
          reader.onload = (e) => {
            let data
            if (typeof e.target.result === 'object') {
              // 把Array Buffer转化为blob 如果是base64不需要
              data = window.URL.createObjectURL(new Blob([e.target.result]))
            } else {
              data = e.target.result
            }
            if (num === 1) {
              this.option.img = data
            } else if (num === 2) {
              this.example2.img = data
            }
          }
          // 转化为base64
          // reader.readAsDataURL(file)
          // 转化为blob
          reader.readAsArrayBuffer(file)
        },
        //确认截图,上传
        cut(type){
            var formData = new FormData();
            this.$refs.cropper.getCropBlob(res=>{
                //res是裁剪后图片的bolb对象
                formData.append("file",res,this.userId);
                this.$axios.put('/api/attach/upload',formData,
                    {contentType: false, processData: false, headers:{'Content-Type': 'multipart/form-data'}}
                ).then(res=>{

                })
            })
        }
  },
  mounted(){
    this.getDownList()
    console.log(this.attach.customaryUrl)
  },
  watch:{
  
    "attach.customaryUrl":function(val){console.log(val)},
    deep: true //对象内部属性的监听，关键。
  }
};
</script>

<style lang='scss' scoped>
/* 弹性布局 水平居中 */
.show-preview{
    display: flex;  
    justify-content: center;
    }

.preview{
        border-radius: 50%;
        overflow: hidden;
        border:1px solid #cccccc;
        background: #cccccc;
      }
.footerBtn{
    display: flex;
    justify-content: center;
    margin-top: 15px;
}
.box{
        position: relative;
        height: 100%;
    }
    .wrapper{
        position: fixed;
        width: 100%;
        top: 0;
        height: calc(100% - 50px);
    }
    .vue-cropper{
        background: black;
        background-image: none!important;
    }
    .btn{
        height: 50px;
        background: #565656;
        width: 100%;
        padding: 0 15px;
    }
    .btn a{
        color: white;
        font-size: .16rem;
        display: inline-block;
        line-height: 50px;
    }
    .btn a:nth-of-type(1){
        float: left;
    }
    .btn a:nth-of-type(2){
        float: right;
    }
    
    
</style>
